package com.tuling.stu;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.tuling.stu.anno.CacheResult;

/**
 * @author chenhs
 * Created on 2018年1月28日 上午11:34:18
 */
@Component
public class AnnotationContext implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

	ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		Class<CacheResult> crClass = CacheResult.class;
		//从容器中获取加了CacheResult注解的所有Bean
		Map<String, Object> annotationBeans = applicationContext.getBeansWithAnnotation(crClass);
		Set<Entry<String, Object>> entrySet = annotationBeans.entrySet();
		for(Entry<String, Object> entry : entrySet) {
			//获取bean的名字
			String beanId = entry.getKey();									
			//获取bean的类对象
			Class<? extends Object> clazz = entry.getValue().getClass();	
			System.out.println(beanId);
			System.out.println(clazz.getName());
			
			//获取注解类实例
			CacheResult cr = AnnotationUtils.findAnnotation(clazz, crClass);
			if(cr != null) {
				System.out.println(cr.key());
				System.out.println(cr.cacheName());
			}
			
			
			//循环当前类的方法
			Method[] methods = clazz.getMethods();
			for (Method method : methods) {
				CacheResult methodCr = AnnotationUtils.findAnnotation(method, crClass);
				if(methodCr != null) {
					System.out.println(methodCr.key());
					System.out.println(methodCr.cacheName());
				}
				
			}
			
		}
		
	}

}
